const execSync = require('../../common/execSync');

const processError = require('../../common/error');

const message = require('../../common/ansi');

const log = require('../../common/log');

const eventEmitter = require('../../common/eventbus');

const {gulpMaps} = require('./gulpMaps');

const path = require('path');

const { platform, project } = JSON.parse(process.env.autopack_data);

const rule = gulpMaps[project][platform];
/**
 * 开启gulp压缩
 */

let times = rule.length;

let current = 0;

let taskMaps = rule.map((item, i) => {

  return {

    index: i,

    params: item,

    callback: (i, maps) => {

      if (i < times) {

        run(maps[i].params);

      }
    }
  }
});

let gulpWorkpath = path.resolve(__dirname,'../../');

/**
 * 执行压缩任务
 * @param {*} params 压缩哪一个包的指令 
 */
function run(params) {
  
  let { result, error, stdout, stderr } = execSync('gulp '+params,gulpWorkpath);

  if(result){

    current++;

    message.info('gulp压缩->指令 gulp '+params);

    log(2,'gulp压缩->指令 gulp '+params);

    // 判断是否为最后一个指令并且是否有回调
    if (current < times && taskMaps[current].callback instanceof Function) {

      taskMaps[current].callback(current, taskMaps);

    } else {

      // 发射所有gulp任务完成事件
      eventEmitter.emit('gulp.complete');

    }

  }else{

    processError('gulp压缩失败->指令 gulp '+params+'程序退出 详细信息：'+(stderr?stderr:error));

  }

}

module.exports = function () {

  run(taskMaps[0].params);

};